package com.javasm.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;

public class JWTUtil {

    private static final SecretKey SecretKey = Keys.hmacShaKeyFor("qazws15xedcrf1584vplmo265jhnisdbva".getBytes(StandardCharsets.UTF_8));
    private static final long TTL_Millis = 1000 * 60 * 60 * 24 * 7;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String createJwt(Object object) {
        long expMillis = System.currentTimeMillis() + TTL_Millis;
        Date exp = new Date(expMillis);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",object);
        JwtBuilder builder = Jwts.builder()
                .signWith(SecretKey)
                .claims(map)
                .expiration(exp);
        return builder.compact();
    }
    public static <T> T parseJWT(String token,Class<T> tClass) {
        Object object = parseJWT(token);
        try{
            return objectMapper.convertValue(object,tClass);
        } catch (RuntimeException e) {
            throw new RuntimeException("类型转换错误");
        }
    }

    public static Object parseJWT(String token) {
        try{
            JwtParser jwtParser = Jwts.parser()
                    .verifyWith(SecretKey)
                    .build();
            Jws<Claims> jws = jwtParser.parseSignedClaims(token);
            return jws.getPayload().get("data");
        } catch (RuntimeException e) {
            throw new RuntimeException("token解密错误");
        }
    }
}